package com.hznu.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hznu.commonutils.handler.CustomException;
import com.hznu.ucenter.entity.Msg;
import com.hznu.ucenter.entity.Rsu;
import com.hznu.ucenter.entity.Vehicle;
import com.hznu.ucenter.mapper.RsuMapper;
import com.hznu.ucenter.service.MsgService;
import com.hznu.ucenter.service.RsuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hznu.ucenter.service.VehicleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cdd
 * @since 2021-04-02
 */
@Service
public class RsuServiceImpl extends ServiceImpl<RsuMapper, Rsu> implements RsuService {

    @Autowired
    private VehicleService vehicleService;

    @Autowired
    private MsgService msgService;

    @Autowired
    @Qualifier("redisTemplate1")
    private RedisTemplate redisTemplate;

    @Override
    public List<Rsu> getRsuList() {
        List<Rsu> rsus = baseMapper.selectList(null);
        return rsus;
    }

    @Override
    public List<Vehicle> getCarInside(Integer rsuId) {
        QueryWrapper<Vehicle> wrapper = new QueryWrapper<>();
        wrapper.eq("vehicle_rsuid",rsuId);
        List<Vehicle> list = vehicleService.list(wrapper);
        return list;
    }

    @Override
    public List<Msg> getMsgListByRsuId(int rsuId) {

        List<Msg> list = new LinkedList<>();
//        Msg msg = new Msg();
//        msg.setMsgId(2);
//        msg.setRsuId(3);
//        msg.setMsgDetail("前方泥石流发生");

//        redisTemplate.opsForHash().put("RsuMsgs",msg.getMsgId(),msg);
//
        // 前提条件，Redis 中插入的为Hash的数据类型
        int rsuMsgs = redisTemplate.opsForHash().keys("RsuMsgs").size();
        for (int i = 1; i <= rsuMsgs;i++){
            Msg o = (Msg)redisTemplate.opsForHash().get("RsuMsgs",i);
            if(o.getRsuId() == rsuId) {
                list.add(o);
            }
        }
        return list;
    }

    @Override
    public void deleteRsu(int rsuId) {
        QueryWrapper<Rsu> wrapper = new QueryWrapper<>();
        wrapper.eq("rsu_id",rsuId);
        int delete = baseMapper.delete(wrapper);
        if (delete == 0 || delete < 0) {
            throw new CustomException(20001,"rsu删除失败!");
        }
    }

    @Override
    public void addRsu(Rsu rsu) {
        int insert = baseMapper.insert(rsu);
        if(insert == 0) {
            throw new CustomException(20001,"rsu添加失败!");
        }
    }
}
